package com.unitd.comm.spring.aop;

import com.alibaba.fastjson.JSON;
import com.unitd.frame.comm.utils.BeanUtils;
import com.unitd.frame.comm.utils.http.HttpUtils;
import com.unitd.frame.springweb.annotation.Log;
import com.unitd.frame.sso.common.helper.IpHelper;
import com.unitd.frame.sso.common.helper.SSOHelper;
import com.unitd.frame.sso.common.token.SSOToken;
import com.unitd.modules.sys.entity.SysLog;
import com.unitd.modules.sys.service.ISysLogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @desc 系统日志,在spring中处理日志信息的切面处理类
 * @filename LogAspect.java
 * @copyright www.unitd.com
 * @author Hudan
 * @version 1.0
 * @date 2017/3/28
 */
@Aspect
@Component
public class LogAspect {

	@Autowired
	private ISysLogService sysLogService;

	@Pointcut("@annotation(com.unitd.frame.springweb.annotation.Log)")
	public void logPointCut() {
	}

	@Around("logPointCut()")
	public void saveLog(JoinPoint joinPoint) {
		MethodSignature signature = (MethodSignature) joinPoint.getSignature();
		Method method = signature.getMethod();

		SysLog sysLog = new SysLog();
		Log log = method.getAnnotation(Log.class);
		if (log != null) {
			//注解上的描述
			sysLog.setOperation(log.value());
		}

		//请求的方法名
		String className = joinPoint.getTarget().getClass().getName();
		String methodName = signature.getName();
		sysLog.setMethod(className + "." + methodName + "()");

		//请求的参数
		Object[] args = joinPoint.getArgs();
		String params = JSON.toJSONString(args[0]);
		sysLog.setParams(params);

		//获取request
		HttpServletRequest request = HttpUtils.getHttpServletRequest();
		//设置IP地址
		sysLog.setIp(IpHelper.getIpAddr(request));

		//用户名
		SSOToken token = SSOHelper.attrToken(request);
		if(!BeanUtils.isNull(token)) {
			sysLog.setUid(token.getUid());
			sysLog.setUsername(token.getUname());
		}

		sysLog.setCreateDate(new Date());
		//保存系统日志
		sysLogService.insertSelective(sysLog);
	}
}